<?php

namespace Modules\AdminPermission\Services;

use Modules\AdminPermission\Models\Permission;

/**
 * 权限服务
 * @author long2ge
 * @date 2023/12/26 7:50 PM
 * @class PermissionService
 * @package Modules\AdminPermission\Services
 * @describe
 */
class PermissionService
{
    public function store()
    {

    }

    // 更新数据
    public function update()
    {

    }

    // 列表数据
    public function index()
    {

    }

    // 查看单条数据
    public function show()
    {

    }

    // 删除数据
    public function delete()
    {

    }

    public function addPermissionDataByConfig()
    {
        $items = module_path('AdminPermission.config.data');

        foreach ($items as $item) {
            $this->addPermissionData($item);
        }
    }

    protected function addPermissionData(array $item)
    {
        $level = $item['level'];

        $permission = Permission::query()->createOrFirst(
            ['name' => $item['name']],
            [
                'pid' => $item['pid'],
                'level' => $level,
                'description' => $item['description'],
                'status' => 1,
            ]
        );

        $children = $item['children'] ?? [];
        if (empty($children)) {
            return;
        }

        $level = $level + 1;
        foreach ($children as $child) {
            $childItem = [
                    'pid' => $permission->id,
                    'level' => $level,
                ] + $child;

            $this->addPermissionData($childItem);
        }
    }

}
